<template>
    <MainModule>
        <MyConfigTemplate v-model="isEdit" :configs="{ leftConfig, formConfig }" :methods="{ Cancel, SubmitForm }">
            <template #TimeUnit>
                <el-option v-for="item in ParamsObj?.AsyncTaskTimeUnit" :label="item.Title" :value="item.Value"></el-option>
            </template>
        </MyConfigTemplate>
    </MainModule>
</template>
    
<script setup lang="ts">
import { onMounted, onUnmounted, ref, shallowRef } from "vue"
import { MainModule, MyConfigTemplate } from "@/components"
import { OrderConfigsApiUrl, OrderConfigsApi } from "@/api/order_manager/order_configs"
import { leftConfig, formConfig, formData, formRef } from "./setConfigTemplate"
import * as types from "./types"
import { useMainLoading } from "@/hooks/useMainLoading"
import MessageUti from "@/library/utils/MessageUti"
import { AbortApi } from "@/library/utils/request"

const { openMainLoading, closeMainLoading } = useMainLoading()

// 原始数据
const formDataRaw = ref({})
const GetAllConfig = async () => {
    const { Data } = await OrderConfigsApi.GetAllConfig()

    const form = {
        ...Data.SyncServerConfig.SyncConsumeOrderStat,
        ServerName: "SyncConsumeOrderStat"
    }

    formDataRaw.value = { ...form }
    Object.assign(formData.value, form)
}

const ParamsObj = shallowRef<types.ParamsType>()
const Params = async () => {
    const { Data } = await OrderConfigsApi.Params()
    ParamsObj.value = Data
}

const isEdit = ref(false)
const Cancel = () => {
    if (isEdit.value) {
        Object.assign(formData.value, formDataRaw.value)
        isEdit.value = false
        formRef.value?.resetFields()
    }
}

const SubmitForm = async () => {
    const valid = await formRef.value?.validate(() => { })
    if (!valid) { return }

    try {
        await OrderConfigsApi.SetConfig(formData.value)
        MessageUti.showSuccess("提交成功")
        isEdit.value = false
        GetAllConfig()
    } catch (error) { }
}

onMounted(async () => {
    openMainLoading()
    await GetAllConfig()
    await Params()
    closeMainLoading()
})

onUnmounted(() => {
    AbortApi([OrderConfigsApiUrl.GetAllConfig, OrderConfigsApiUrl.Params])
})

</script>
    
<style scoped></style>